#!/bin/bash

# APS项目部署脚本 - 4核16G服务器
# 使用方法: ./deploy.sh [start|stop|restart|status|logs|backup|health]

set -e

PROJECT_NAME="aps-system"
COMPOSE_FILE="docker-compose.yml"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 打印信息
info() { echo -e "${GREEN}[INFO]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }
success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }

# 检查Docker环境
check_requirements() {
    info "检查环境依赖..."
    
    if ! command -v docker &> /dev/null; then
        error "Docker未安装，请先安装Docker"
        echo "安装命令: curl -fsSL https://get.docker.com | sh"
        exit 1
    fi
    success "Docker已安装 ✓"

    if ! docker compose version &> /dev/null; then
        error "Docker Compose未安装或版本过低"
        exit 1
    fi
    success "Docker Compose已安装 ✓"
    
    if ! docker info &> /dev/null; then
        error "Docker服务未运行"
        echo "启动命令: sudo systemctl start docker"
        exit 1
    fi
    success "Docker服务运行中 ✓"
}

# 创建必要的目录
create_directories() {
    info "创建必要的目录..."
    mkdir -p data/mysql data/redis logs/backend logs/nginx init/sql nginx backup
    
    # 尝试设置权限，如果失败则尝试使用sudo或忽略
    if chmod -R 777 data logs 2>/dev/null; then
        success "目录权限设置完成 ✓"
    else
        warn "部分目录权限设置失败，尝试使用sudo..."
        if command -v sudo &> /dev/null; then
            sudo chmod -R 777 data logs 2>/dev/null || warn "权限设置失败，但继续执行..."
        else
            warn "无法设置权限，如果后续有权限问题，请手动执行: sudo chmod -R 777 data logs"
        fi
    fi
    
    success "目录创建完成 ✓"
}

# 配置环境变量
setup_env() {
    if [ ! -f .env ]; then
        if [ -f .env.template ]; then
            info "创建环境变量文件..."
            cp .env.template .env
            warn "⚠️  请立即编辑 .env 文件，修改数据库密码！"
            warn "⚠️  编辑命令: vim .env 或 nano .env"
            read -p "按回车键继续..." 
        else
            error ".env.template 文件不存在"
            exit 1
        fi
    else
        success "环境变量文件已存在 ✓"
    fi
}

# 启动服务
start() {
    echo ""
    echo "=========================================="
    echo "  启动 ${PROJECT_NAME}"
    echo "=========================================="
    echo ""
    
    check_requirements
    create_directories
    setup_env
    
    info "启动Docker容器..."
    docker compose -f ${COMPOSE_FILE} up -d
    
    echo ""
    success "=========================================="
    success "  服务启动成功！"
    success "=========================================="
    echo ""
    
    info "服务访问地址："
    echo "  📱 前端页面:    http://localhost"
    echo "  🔧 后端API:     http://localhost:8080"
    echo "  📚 API文档:     http://localhost:8080/doc.html"
    echo "  ❤️  健康检查:    http://localhost:8080/actuator/health"
    echo ""
    
    warn "⚠️  首次启动需要5-10分钟构建镜像，请耐心等待..."
    info "查看实时日志: docker compose logs -f"
}

# 停止服务
stop() {
    info "停止${PROJECT_NAME}..."
    docker compose -f ${COMPOSE_FILE} down
    success "服务已停止 ✓"
}

# 重启服务
restart() {
    info "重启${PROJECT_NAME}..."
    stop
    sleep 2
    start
}

# 查看状态
status() {
    echo ""
    echo "=========================================="
    echo "  服务状态"
    echo "=========================================="
    echo ""
    
    docker compose -f ${COMPOSE_FILE} ps
    
    echo ""
    echo "=========================================="
    echo "  资源使用情况"
    echo "=========================================="
    echo ""
    
    docker stats --no-stream
}

# 查看日志
logs() {
    if [ -z "$2" ]; then
        info "查看所有服务日志..."
        docker compose -f ${COMPOSE_FILE} logs -f --tail=100
    else
        info "查看 $2 服务日志..."
        docker compose -f ${COMPOSE_FILE} logs -f --tail=100 $2
    fi
}

# 健康检查
health() {
    echo ""
    echo "=========================================="
    echo "  健康检查"
    echo "=========================================="
    echo ""
    
    # 检查MySQL
    if docker exec aps-mysql mysqladmin ping -h localhost --silent 2>/dev/null; then
        success "MySQL: ✓ 运行正常"
    else
        error "MySQL: ✗ 运行异常"
    fi
    
    # 检查Redis
    if docker exec aps-redis redis-cli ping 2>/dev/null | grep -q PONG; then
        success "Redis: ✓ 运行正常"
    else
        error "Redis: ✗ 运行异常"
    fi
    
    # 检查后端
    if curl -sf http://localhost:8080/actuator/health > /dev/null 2>&1; then
        success "Backend: ✓ 运行正常"
    else
        error "Backend: ✗ 运行异常"
    fi
    
    # 检查前端
    if curl -sf http://localhost > /dev/null 2>&1; then
        success "Frontend: ✓ 运行正常"
    else
        error "Frontend: ✗ 运行异常"
    fi
    
    echo ""
}

# 备份数据
backup() {
    BACKUP_DIR="backup/$(date +%Y%m%d_%H%M%S)"
    info "备份数据到 ${BACKUP_DIR}..."
    
    mkdir -p ${BACKUP_DIR}
    
    # 读取环境变量
    if [ -f .env ]; then
        source .env
    fi
    
    # 备份MySQL
    info "备份MySQL数据库..."
    docker exec aps-mysql mysqldump -u root -p${MYSQL_ROOT_PASSWORD:-Jsyshiyou@0723} ${MYSQL_DATABASE:-aps_example} > ${BACKUP_DIR}/mysql_backup.sql
    
    # 备份Redis
    info "备份Redis数据..."
    docker exec aps-redis redis-cli -a ${REDIS_PASSWORD:-123456} BGSAVE
    sleep 2
    docker cp aps-redis:/data/dump.rdb ${BACKUP_DIR}/redis_backup.rdb
    
    # 备份配置文件
    info "备份配置文件..."
    cp .env ${BACKUP_DIR}/ 2>/dev/null || true
    cp ${COMPOSE_FILE} ${BACKUP_DIR}/ 2>/dev/null || true
    
    success "备份完成: ${BACKUP_DIR} ✓"
    info "备份文件列表:"
    ls -lh ${BACKUP_DIR}
}

# 显示帮助信息
help() {
    cat << EOF

========================================
  APS项目部署脚本
========================================

使用方法:
  ./deploy.sh [命令]

命令:
  start         启动所有服务
  stop          停止所有服务
  restart       重启所有服务
  status        查看服务状态和资源使用
  logs          查看所有日志 (可选: logs [service-name])
  health        健康检查
  backup        备份数据
  help          显示此帮助信息

示例:
  ./deploy.sh start                 # 启动服务
  ./deploy.sh logs aps-backend      # 查看后端日志
  ./deploy.sh status                # 查看状态
  ./deploy.sh backup                # 备份数据

EOF
}

# 主逻辑
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    logs)
        logs $@
        ;;
    health)
        health
        ;;
    backup)
        backup
        ;;
    help|--help|-h|"")
        help
        ;;
    *)
        error "未知命令: $1"
        help
        exit 1
        ;;
esac

